package com.lyun.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyun.mapper.CommentMapper;
import com.lyun.pojo.Comment;
import com.lyun.service.CommentLikeService;
import com.lyun.service.CommentService;
import com.lyun.vo.CommentsVo;
import com.lyun.vo.PageVO;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Resource
    private CommentMapper commentMapper;

    @Resource
    private CommentLikeService commentLikeService;

    @Override
    public int getCommentCount(Long movementId) {
        return commentMapper.getCommentCountByMovementId(movementId);
    }

    /**
     * @param id         用户id
     * @param movementId 动态id
     * @param page       分页页码
     * @param pagesize   每页显示条数
     * @return
     */
    @Override
    public PageVO<CommentsVo> getCommentsVoPageByMovementId(Long id, Long movementId, Integer page, Integer pagesize) {
        //先联表查询获得这条动态底下的 评论和评论人信息
        List<CommentsVo> list = commentMapper.getCommentsVoListByMovementId(movementId);

        PageVO<CommentsVo> vo = new PageVO<>();

        int size = list.size();
        vo.setCounts((long) size);
        vo.setPageSize(pagesize);
        vo.setPages((long) Math.ceil((double) size / pagesize));
        vo.setPage(page);

        if (size == 0) {
            vo.setItems(list);
            return vo;
        }

        //还有两个字段 likeCount hasLiked 没填
        list = list.stream().peek((commentsVo) -> {
            int likeCount = commentLikeService.getCommentsLikeCount(Long.valueOf(commentsVo.getId()));

            int isLike = commentLikeService.getIsLikeByUserIdAndCommentId(id, Long.valueOf(commentsVo.getId()));

            commentsVo.setLikeCount(likeCount);
            commentsVo.setHasLiked(isLike);
        }).collect(Collectors.toList());

        for (CommentsVo commentsVo : list) {
            System.out.println("commentsVo = " + commentsVo);
        }
        vo.setItems(list);

        return vo;
    }
}
